package cn.example.project1.service.impl;

import cn.example.base.service.impl.BaseServiceImpl;
import cn.example.project1.dao.MsgDAO;
import cn.example.project1.po.Msg;
import cn.example.project1.service.MsgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * Created by WuYB on 2017/6/19.
 */
@Service
public class MsgServiceImpl extends BaseServiceImpl<Msg> implements MsgService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private MsgDAO msgDAO;

    @Override
//    @Transactional//默认只检查RuntimeException，其余不会回滚
    @Transactional(rollbackFor = Exception.class)
    public boolean insertList(List<Msg> list) throws IOException {
//        try {
        int i = 0;
        for (Msg s : list) {
            if (i > 5) {
//                    throw new IOException("测试异常" + s.getMsg());
                rollBack();
                return false;
            }
            msgDAO.insert(s);
            i++;
        }
        return true;
//        } catch (Exception e) {
//            log.info("事务发生异常:", e);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕捉异常后手动回滚
//            return false;
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertLists(List<Msg> list) throws IOException {
        msgDAO.insert(new Msg("out1", "e"));
        insertList(list);
        msgDAO.insert(new Msg("out2", "e"));
//        if (randomUtil.random(0, 10) > 0) {
//            throw new IOException("测试外部异常");
//        }
        msgDAO.insert(new Msg("out3", "e"));
        return true;
    }
}
